<template>
  <b-page class="member-qywx ">
    <a-alert
      v-if="!hasAuth"
      message="提示"
      description="企业通讯录是企业的重要敏感数据，第三方将不再直接获取到授权企业的通讯录数据，需要单独授权，否则只能获取到拼音的用户id。扫描以下二维码确认授权。"
      type="error"
      show-icon
    />
    <a-alert
      v-if="isExportLoading"
      message="提示"
      description="企业微信成员同步中，预计需要5-10分钟，请稍后查看！"
      type="success"
      show-icon
    />
    <div class="gzh-qywx-desc">
      <div class="desc-title">提示</div>
      <div class="desc-content" v-for="(item,index) in descList" :key="index" v-html="item"></div>
    </div>
    <!--    内部应用授权-->
    <div v-if="!hasAuth" class="qr-code-wrap">
      <img :src="qrCode" style="width: 100%">
      使用企业微信扫码授权
      <div v-if="bindOverTime" class="qr-code-error" @click="initAuth">
        <a-icon type="sync" class="x-icon"/>
        二维码已超时，点击刷新
      </div>
    </div>
    <!--    end-->
    <div class="table-page-search-wrapper mt-20">
      <a-row :gutter="48">
        <a-col :md="12" :sm="24">
          <a-input
            v-model="queryParam.blurry"
            placeholder="请输入成员姓名或编号"
            style="margin-right: 8px;width: 200px;"/>
          <a-button type="primary" @click="$refs.table.refresh(true)">查询</a-button>
          <!--          <a-button style="margin-left: 8px" @click="() => queryParam = {}">重置</a-button>-->
        </a-col>
        <a-col :md="12">
          <div style="display: flex;justify-content: flex-end;align-items: center">
            <a-select
              v-model="queryParam.active"
              placeholder="请选择"
              :default-value="0"
              style="margin-right: 8px;width: 128px;"
              @change="changeActive">
              <a-select-option :value="1">裂变成员</a-select-option>
              <a-select-option :value="0">全部成员</a-select-option>
            </a-select>
            <b-button btn-content="从企业微信导入" @click="exportMember" :loading="isExportLoading"/>
          </div>
        </a-col>
      </a-row>
      <div class="update-desc-state d-jcc-aic" v-if="isExportLoading">
        <div style="height: 20px"> 正在从企业微信导入，请等待...</div>
        <div class="material-icons desc-state-icon">autorenew</div>
      </div>
    </div>
    <s-table
      ref="table"
      rowKey="id"
      size="default"
      :columns="columns"
      :data="loadData"
      :pageSize="10"
    >
      <span slot="username" slot-scope="text, record">
        <img v-if="record.avatar" style="width: 40px;height:40px;border-radius:50%" :src="record.avatar">
        <img v-else style="width: 40px;height:40px;border-radius:50%" src="../../assets/avatar.png">
        <span style="margin-left: 10px">{{ record.name }}</span>
      </span>
      <span slot="active" slot-scope="text, record">
        <a-popconfirm
          v-if="!record.active"
          title="一旦设定为裂变成员，就不能再取消！"
          ok-text="确定"
          cancel-text="再想想"
          @confirm="activeChange(record)"
        >
          <a-switch :checked="!!record.active"/><span
            style="margin-left: 10px">{{ record.active?'是':'否' }}</span>
        </a-popconfirm>
        <template v-else>
          <a-switch :disabled="true" :checked="!!record.active"/>
          <span style="margin-left: 10px">{{ record.active?'是':'否' }}</span>
        </template>
      </span></s-table>
    </a-alert></b-page>
</template>

<script>
    import { STable } from '@/components'
    import BButton from '../../components/b-button'
    import { qwMemberPage, active, checkRunningSyncTask, syncMembers } from '../../../api/common'
    import QwAuth from '@/perm/api/qwAuth'

    export default {
        name: 'MemberQywx',
        components: {
            BButton,
            STable
        },
        data () {
            return {
                // 查询参数
                queryParam: { active: 0, blurry: '' },
                // 表头
                columns: [
                    {
                        title: '编号',
                        width: '150px',
                        dataIndex: 'id'
                    },
                    {
                        title: '成员',
                        dataIndex: 'username',
                        scopedSlots: { customRender: 'username' }
                    },
                    {
                        title: '手机号',
                        width: '300px',
                        dataIndex: 'phone'
                    },
                    {
                        title: '是否裂变成员',
                        width: '150px',
                        dataIndex: 'active',
                        scopedSlots: { customRender: 'active' }
                    }
                ],
                // 加载数据方法 必须为 Promise 对象
                loadData: parameter => {
                    const qwUserId = this.$store.state.user.info.qwUserId || null
                    const params = Object.assign({
                        qwUserId: qwUserId,
                        size: parameter.pageSize
                    }, this.queryParam)
                    return qwMemberPage(Object.assign({
                        current: parameter.pageNo,
                        size: parameter.pageSize
                    }, params))
                        .then(res => {
                            return {
                                data: res.records,
                                'pageSize': res.size,
                                'pageNo': res.current,
                                'totalCount': res.total
                            }
                        })
                },
                descList: [
                    ' 未激活的成员无法生成名片二维码，因此无法被选中为裂变成员，<a target="_blank" class="member-qywx-a" href="https://www.yuque.com/docs/share/317db508-0011-4c0c-89e2-78f7c89fd9d1?#">如何激活</a>'
                ],
                selectedRowKeys: [],
                selectedRows: [],
                // custom table alert & rowSelection
                options: {},
                isExportLoading: false,
                qrCodeKey: '',
                qrCode: '',
                bindOverTime: false
            }
        },
        computed: {
            userInfo () {
                return this.$store.state.user.info
            },
            qwUserId () {
                return this.$store.state.user.info.qwUserId
            },
            hasAuth () {
                // 通过是否有内部企业应用id判断是否已授权
                return !!this.$store.state.user.info.agentId
            }
        },
        created () {
            this.options = {
                alert: {
                    show: true,
                    clear: () => {
                        this.selectedRowKeys = []
                    }
                },
                rowSelection: {
                    selectedRowKeys: this.selectedRowKeys,
                    onChange: this.onSelectChange
                }
            }
        },
        mounted () {
            this.checkRunningTask()
            // this.bindSuccess()
            this.initAuth()
        },
        methods: {
            async initAuth () {
                // TODO 检查是否已授权，userInfo里面是否有app_id
                if (this.hasAuth) {
                    return
                }
                // 获取收钱qrkey
                this.qrCodeKey = await QwAuth.getQrCodeKey()
                this.qrCode = 'api/qw/wx-work-mock/getQrCode/' + this.qrCodeKey
                // 每轮只尝试10次，30秒，之后会显示二维码异常，请刷新
                // 轮询检查是否扫描
                this.bindOverTime = false
                this.checkStatus(0)
            },
            // 持续检查是否被扫码, 超时
            checkStatus (i) {
                console.log(i)
                if (i > 5) {
                    this.bindOverTime = true
                    return
                }
                QwAuth.checkStatus({
                    qrCodeKey: this.qrCodeKey,
                    corpId: this.userInfo.corpId,
                    qwUserId: this.qwUserId
                }).then(res => {
                    if (res === 'QRCODE_SCAN_NEVER') {
                        // 还未扫码，等待3秒后，再次执行
                        setTimeout(() => {
                            this.checkStatus(i + 1)
                        }, 3000)
                    } else if (res === 'QRCODE_SCAN_SUCC') {
                        location.reload()
                    } else {
                        console.log('扫码出现异常')
                        // 重新生成二维码
                        this.initAuth()
                    }
                }).catch(err => {
                    console.log('扫码结果出现异常', err)
                    this.bindError(err)
                })
            },
            /**
             * 绑定成功
             */
            bindSuccess () {
                this.$success({
                    title: '绑定成功',
                    content: '接下来将同步通讯录数据，请稍候...',
                    okText: '好'
                })
            },
            /**
             * 绑定失败
             */
            bindError (error) {
                // 使用不同的企业扫码错误
                // 使用扫码管理权限不够
                // 企业微信已安装应用
                this.$error({
                    title: '绑定失败',
                    content: error.msg + '。更多帮助请咨询专属客服',
                    okText: '咨询客服'
                })
            },
            changeActive () {
                this.$refs.table.refresh(true)
            },
            checkRunningTask () {
                checkRunningSyncTask({ qwUserId: this.qwUserId }).then(res => {
                    if (this.isExportLoading && !res.synchronizing) {
                        this.$message.success(`导入完成`)
                        this.isExportLoading = false
                        this.changeActive()
                    }
                    if (res.synchronizing) {
                        this.isExportLoading = true
                        setTimeout(() => {
                            this.checkRunningTask()
                        }, res.remaining + 2000)
                    }
                })
            },
            exportMember () {
                if (this.isExportLoading) {
                    this.$message.warning(`正在导入，请等待。。。`)
                    return
                }
                syncMembers({ qwUserId: this.qwUserId }).then(res => {
                    this.isExportLoading = true
                    this.$message.warning(`正在同步，请等待。。。`)
                    setTimeout(() => {
                        this.checkRunningTask()
                    }, 5000)
                })
            },
            onSelectChange (selectedRowKeys, selectedRows) {
                this.selectedRowKeys = selectedRowKeys
                this.selectedRows = selectedRows
            },
            activeChange (record) {
                if (record.active) {
                    this.$message.warning(`裂变成员不能取消`)
                    return
                }
                active({ memberId: record.id, qwUserId: this.qwUserId }).then(res => {
                    record.active = 1
                    this.$message.success(`激活裂变成员成功`)
                }).catch(() => {
                    this.$message.error('该成员未激活，请该成员登录企业微信激活后再试')
                })
            }
        }
    }
</script>

<style scoped lang="less">
    .member-qywx {
        .member-qywx-a {
            color: #0c8eff;
        }

        .gzh-qywx-desc {
            margin-bottom: 10px;
            padding: 18px 13px;
            min-width: 768px;
            line-height: 20px;
            background-color: rgba(255, 251, 231, 100);
            color: rgba(250, 173, 19, 100);
            font-size: 14px;
            border: 1px solid rgba(255, 228, 175, 100);

            .desc-title {
                margin-bottom: 16px;
                font-size: 20px;
                color: #262626;
            }

            .desc-content {
                font-size: 14px;
                color: #595959;
            }
        }

        .table-page-search-wrapper {
            position: relative;
            padding-bottom: 30px;
            border-bottom: 1px solid #D9D9D9;

            .update-desc-state {
                position: absolute;
                right: 0;
                bottom: 0;
                height: 30px;
                font-size: 12px;
                color: #52C41A;

                .desc-state-icon {
                    margin-left: 8px;
                    font-size: 20px;
                    animation: syncAnimal 1.5s forwards infinite;
                }
            }
        }

        .qr-code-wrap {
            position: relative;
            margin: 20px auto;
            width: 200px;
            display: flex;
            flex-direction: column;
            align-items: center;
            justify-content: center;
        }

        .qr-code-error {
            position: absolute;
            left: -5%;
            top: -5%;
            width: 110%;
            height: 110%;
            background: rgba(33, 33, 33, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            flex-direction: column;
            color: white;

            .x-icon {
                color: #f5222d;
                font-size: 50px;
            }
        }
    }

</style>
